package com.moogene.android.engine.mmi.widget;

import com.moogene.android.InfoMediator;
import com.moogene.android.engine.animlite.Animlite;
import com.moogene.android.engine.animlite.ScaleAnim;
import com.moogene.android.engine.mmi.Book;
import com.moogene.android.engine.util.Anchor;

import android.graphics.Bitmap;
import android.graphics.Canvas;

public class IconButton extends Widget {
	private Animlite bgAnim;

	private Animlite iconAnim;

	private boolean isPoppingup;

	private boolean isShrink;

	public IconButton(Bitmap bg, Bitmap icon) {
		super();
		this.iconAnim = new Animlite(icon);
		this.bgAnim =  new Animlite(bg, 1, 2);
		width = bgAnim.getFrameWidth();
		height = bgAnim.getFrameHeight();
		setAnchor(Anchor.CENTER);
		iconAnim.setAnchor(Anchor.CENTER);
		bgAnim.setAnchor(Anchor.CENTER);
	}

	public IconButton(int bgID, int iconID) {
        this(InfoMediator.getBitmap(bgID), InfoMediator.getBitmap(iconID));
    }

	public void popup() {
		bgAnim.getScaleAnim().start(0, 1.4, 0.2);
		iconAnim.getScaleAnim().start(0, 1.4, 0.2);
		isPoppingup = true;
		isShrink = false;
	}

	public void shrink() {
		if (bgAnim.getScaleAnim().getCurrent() > 0) {
			bgAnim.getScaleAnim().start(0, -0.2);
			iconAnim.getScaleAnim().start(0, -0.2);
			isShrink = true;
			isPoppingup = false;
		}
	}

	public void setTransparent(int alpha) {
		bgAnim.getAlphaAnim().setAlpha(alpha);
		iconAnim.getAlphaAnim().setAlpha(alpha);
	}

	@Override
	public void update() {
		super.update();
		if (isPoppingup) {
			ScaleAnim sa = bgAnim.getScaleAnim();
			if (sa.isPaused()) {
				if (sa.getCurrent() > 1.2) {
					sa.start(1, -0.2);
					iconAnim.getScaleAnim().start(1, -0.2);
				} else {
					isPoppingup = false;
				}
			}
		}
		if (isShrink) {
			ScaleAnim sa = bgAnim.getScaleAnim();
			if (sa.isPaused()) {
				Book.getInstance().removeLayer(this);
				isShrink = false;
			}
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.moogene.android.engine.mmi.Layer#draw(android.graphics.Canvas)
	 */
	@Override
	protected void onDraw(Canvas canvas) {
		if (isHold()) {
			bgAnim.getFrameAnim().setFrame(1);
		} else {
			bgAnim.getFrameAnim().setFrame(0);
		}
		bgAnim.draw(canvas, x, y);
		iconAnim.draw(canvas, x, y);
	}

}
